from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_userDataEdit
import hashlib

class UserDataEdit(QDialog, Ui_userDataEdit.Ui_userDataEditDlg):
    
  StyleSheet = """
QLineEdit[mandatory="true"] {
    background-color: rgb(255, 255, 127);
    color: darkblue;
}
"""

  def __init__(self, dbConn, tipe,  dataGlob, parent=None):
        super(UserDataEdit, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.tipe = tipe
        self.dataGlob = dataGlob
        self.passChange = False
        self.initData()
        
        self.mastModel = QSqlTableModel(self)
        self.mastModel.setTable("master_user")
        self.mastModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.lineedits = (self.userId_le, self.pwd_le,self.pwd2_le, self.nama_le, self.level_le,  self.status_le,  self.id_le)
        for lineEdit in self.lineedits:
            lineEdit.setProperty("mandatory", QVariant(True))
        self.setStyleSheet(UserDataEdit.StyleSheet)
        
  @pyqtSignature("")
  def on_simpan_pb_clicked(self):
      if self.tipe == "add":
          if self.tambahData():
              self.close()
          else:
              QMessageBox.warning(self, "Master User","Tidak berhasil menambah data.")
      else:
          if self.updateData():
              self.close()
          else:
              QMessageBox.warning(self, "Master User","Data tidak berhasil disimpan.")
      
  @pyqtSignature("")
  def on_batal_pb_clicked(self):
      self.close()
      
  @pyqtSignature("QString")
  def on_pwd_le_textEdited(self,  newPass):
      self.passChange = True
      
  def tambahData(self):
      if not self.validasi():          
          return
      self.mastModel.select()      
      QSqlDatabase.database().transaction()
      if not self.mastModel.insertRow(0):
          return
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.id_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.userId_le.text()))
      m = hashlib.md5()
      m.update(self.pwd_le.text())
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(m.hexdigest()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.nama_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant("NA"))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.level_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(self.ket_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(self.status_le.text()))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def updateData(self):
      if not self.validasi():
          return
      self.mastModel.setFilter("id_user = '"+self.tipe+"'")
      self.mastModel.select()      
      QSqlDatabase.database().transaction()
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.userId_le.text()))
      if self.passChange:
          m = hashlib.md5()
          m.update(self.pwd_le.text())
          self.mastModel.setData(self.mastModel.index(0, 2), QVariant(m.hexdigest()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.nama_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant("NA"))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.level_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(self.ket_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(self.status_le.text()))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def initData(self):
      if self.tipe != "add":
          query = QSqlQuery(self.db)
          qStr = "select id_user, kode_user, pass_user, nama, grup_menu, level_user, ket, stat_user from master_user where id_user = '"+self.tipe+"'"
          query.exec_(qStr)
          query.next()
          self.id_le.setText(unicode(query.value(0).toString()))
          self.userId_le.setText(unicode(query.value(1).toString()))
          self.pwd_le.setText(unicode(query.value(2).toString()))
          self.pwd2_le.setText(unicode(query.value(2).toString()))
          self.nama_le.setText(unicode(query.value(3).toString()))
          self.level_le.setText(unicode(query.value(5).toString()))
          self.ket_le.setText(unicode(query.value(6).toString()))
          self.status_le.setText(unicode(query.value(7).toString()))
      
  def validasi(self):
      for lineEdit in self.lineedits:
           if lineEdit.text().isEmpty():
               QMessageBox.warning(self, "Master User","Data yang diinput tidak valid / Kolom kosong.")
               return False
               
      if self.pwd_le.text() != self.pwd2_le.text():
          QMessageBox.warning(self, "Master User","Password yang diinput tidak sama.")
          return False
          
      if len(self.pwd_le.text()) < 6:
          QMessageBox.warning(self, "Master User","Password minimal 6 karakter")
          return False
          
      return True

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = UserDataEdit()
    form.show()
    app.exec_()
